package com.triones.biz.infra.controller.api.ocr;

import cn.dev33.satoken.annotation.SaIgnore;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONUtil;
import com.aliyun.ocr_api20210707.models.*;
import com.aliyun.tea.TeaException;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.exception.ServiceException;
import com.triones.biz.infra.service.ocr.AliyunSampleServer;
import com.triones.biz.infra.service.ocr.BaiduOcrAuthServe;
import com.triones.biz.infra.service.ocr.utils.AccurateBasic;
import com.triones.biz.infra.service.ocr.utils.Base64Util;
import com.triones.biz.infra.service.ocr.utils.HttpUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * API - 文字识别api
 *
 * @author triones
 * 2023-09-25
 */
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/ocr")
@Validated
@Slf4j
public class ApiOcrController {

    /**
     * 图片识别
     */
    @PostMapping
    @SaIgnore
    public void getIm(MultipartFile file) throws IOException {
        AccurateBasic.accurateBasic(file.getBytes());
    }

    @SaIgnore
    @PostMapping("/aliyun")
    public R<Map> aliyunOcr(MultipartFile file) throws Exception {
        Map resMap = new HashMap();
        com.aliyun.ocr_api20210707.Client client = AliyunSampleServer.createClient();
        java.io.InputStream bodySyream = file.getInputStream();
        RecognizeAdvancedRequest request = new RecognizeAdvancedRequest().setBody(bodySyream)
            .setOutputCharInfo(true)
            .setOutputTable(true)
            .setNeedSortPage(false)
            .setRow(true);
        try {
            RecognizeAdvancedResponse response = client.recognizeAdvanced(request);
            RecognizeAdvancedResponseBody body = response.getBody();
            String data = body.getData();
            Map map = JSONUtil.toBean(data, Map.class);
            List<Map> list = JSONUtil.toList(map.get("prism_rowsInfo").toString(), Map.class);

            String regEx = "[^0-9]";
            Pattern compile = Pattern.compile(regEx);
            Matcher grossWeightM = compile.matcher(list.get(list.size() - 3).get("word").toString());
            Matcher tareWeightM = compile.matcher(list.get(list.size() - 2).get("word").toString());
            Matcher weightM = compile.matcher(list.get(list.size() - 1).get("word").toString());

            String grossWeight = grossWeightM.replaceAll("").trim();
            String tareWeight = tareWeightM.replaceAll("").trim();
            String weight = weightM.replaceAll("").trim();

            if ("".equals(grossWeight) || "".equals(tareWeight) || "".equals(weight)) {
                throw new ServiceException("照片无法识别，请手动输入数据");
            }

            resMap.put("grossWeight",grossWeight);
            resMap.put("tareWeight",tareWeight);
            resMap.put("weight",weight);
            return R.ok(resMap);
        } catch (TeaException error) {
            throw new ServiceException("照片无法识别，请手动输入数据");
        } catch (Exception error) {
            throw new ServiceException("照片无法识别，请手动输入数据");
        }
    }

    @SaIgnore
    @PostMapping("/baidu")
    public Object baidu(MultipartFile file) throws Exception {
        // 请求url
        String url = "https://aip.baidubce.com/rest/2.0/ocr/v1/weight_note";
        try {
            String imgStr = Base64Util.encode(file.getBytes());
            String imgParam = URLEncoder.encode(imgStr, "UTF-8");
            String param = "image=" + imgParam;
            String result = HttpUtil.post(url, BaiduOcrAuthServe.getAuth(), param);
            System.out.println("识别的信息" + result);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
